#include "texteditor.h"
#include "mdichild.h"
#include <QMdiSubWindow>
#include <QFileDialog>
#include <QFileInfo>
#include <QSettings>
#include <QCloseEvent>

texteditor::texteditor(QWidget *parent)
	: QMainWindow(parent)
{
	ui.setupUi(this);
    actionSeperator = new QAction(this);
    actionSeperator->setSeparator(true);
    updateMenu();
    connect(ui.mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)), this, SLOT(updateMenu()));
    windowsMapper = new QSignalMapper(this);
    connect(windowsMapper, SIGNAL(mapped(QWidget*)), this, SLOT(setActiveWindow(QWidget*)));
    connect(ui.menu_Window, SIGNAL(aboutToShow()), this, SLOT(updateWindowMenu()));
    readSettings();
}

texteditor::~texteditor()
{

}

void texteditor::updateMenu()
{
    bool hasChild = (activeSubWindow() != 0);
    ui.action_Save->setEnabled(hasChild);
    ui.action_SaveAs->setEnabled(hasChild);
    ui.action_Paste->setEnabled(hasChild);
    ui.action_Close->setEnabled(hasChild);
    ui.action_CloseAll->setEnabled(hasChild);
    ui.action_Cascade->setEnabled(hasChild);
    ui.action_Title->setEnabled(hasChild);
    ui.action_Next->setEnabled(hasChild);
    ui.action_Previous->setEnabled(hasChild);

    actionSeperator->setVisible(hasChild);

    bool hasSelection = (activeSubWindow() && activeSubWindow()->textCursor().hasSelection());
	ui.action_Copy->setEnabled(hasSelection);
	ui.action_Cut->setEnabled(hasSelection);

	ui.action_Undo->setEnabled(activeSubWindow() && activeSubWindow()->document()->isUndoAvailable());
    ui.action_Redo->setEnabled(activeSubWindow() && activeSubWindow()->document()->isRedoAvailable());
}

void texteditor::updateWindowMenu()
{
    ui.menu_Window->clear();
    ui.menu_Window->addAction(ui.action_Close);
    ui.menu_Window->addAction(ui.action_CloseAll);
    ui.menu_Window->addSeparator();
    ui.menu_Window->addAction(ui.action_Title);
    ui.menu_Window->addAction(ui.action_Cascade);
    ui.menu_Window->addSeparator();
    ui.menu_Window->addAction(ui.action_Next);
    ui.menu_Window->addAction(ui.action_Previous);
    ui.menu_Window->addAction(actionSeperator);

    QList<QMdiSubWindow*> list = ui.mdiArea->subWindowList();
    for(int i=0; i<list.size(); i++)
    {
        mdiChild* child = qobject_cast<mdiChild*>(list.at(i)->widget());
        QString text;
        if(i<9)
            text = QString("&%1 %2").arg(i+1).arg(child->userFriendlyCurrentFile());
        else
            text = QString("%1 %2").arg(i+1).arg(child->userFriendlyCurrentFile());

        QAction* action = ui.menu_Window->addAction(text);
        action->setCheckable(true);
        if(child == activeSubWindow())
            action->setChecked(true);

        connect(action, SIGNAL(triggered()), windowsMapper, SLOT(map()));
        windowsMapper->setMapping(action, list.at(i));

    }
}

void texteditor::on_action_New_triggered()
{
    mdiChild* child = createMdiChild();
    ui.mdiArea->addSubWindow(child);
    child->newFile();
    child->show();
}

mdiChild *texteditor::activeSubWindow()
{
    QMdiSubWindow* subWindow = ui.mdiArea->activeSubWindow();
    if(subWindow)
        return qobject_cast<mdiChild*>(subWindow->widget());
    return 0;
}

mdiChild* texteditor::createMdiChild()
{
    mdiChild* child = new mdiChild(this);
    connect(child->document(), SIGNAL(undoAvailable(bool)), ui.action_Undo, SLOT(setEnabled(bool)));
    connect(child->document(), SIGNAL(redoAvailable(bool)), ui.action_Redo, SLOT(setEnabled(bool)));
    connect(child, SIGNAL(copyAvailable(bool)), ui.action_Copy, SLOT(setEnabled(bool)));
    connect(child, SIGNAL(copyAvailable(bool)), ui.action_Cut, SLOT(setEnabled(bool)));
    return child;
}

QMdiSubWindow *texteditor::getExistingSubWindow(const QString& filePath)
{
    QString canonicalFilePath = QFileInfo(filePath).canonicalFilePath();
    if(canonicalFilePath.isEmpty())
        return 0;
    foreach (QMdiSubWindow* window, ui.mdiArea->subWindowList()) {
        mdiChild* child = qobject_cast<mdiChild*>(window->widget());
        if(child->getCurrentFileName() == canonicalFilePath)
            return window;
    }
    return 0;
}

void texteditor::readSettings()
{
    QSettings setting("msl", "TextEditor");
    QPoint pos = setting.value("pos", QPoint(200,200)).toPoint();
    QSize size = setting.value("size", QSize(400,400)).toSize();
    move(pos);
    resize(size);
}

void texteditor::writeSettings()
{
    QSettings setting("msl","TextEditor");
    setting.setValue("pos", pos());
    setting.setValue("size", size());
}

void texteditor::on_action_Open_triggered()
{
    QString filePath = QFileDialog::getOpenFileName(this);
    if(filePath.isEmpty())
        return;
    QMdiSubWindow* window = getExistingSubWindow(filePath);
    if(window)
        setActiveWindow(window);
    else
    {
        mdiChild* child = new mdiChild(this);
        ui.mdiArea->addSubWindow(child);
        child->loadFile(filePath);
        child->show();
    }
}

void texteditor::setActiveWindow(QWidget *window)
{
    ui.mdiArea->setActiveSubWindow(qobject_cast<QMdiSubWindow*>(window));
}

void texteditor::on_action_Save_triggered()
{
    if(activeSubWindow() && activeSubWindow()->save())
        ui.statusBar->showMessage(tr("文件保存成功"), 2000);
}

void texteditor::on_action_SaveAs_triggered()
{
    if(activeSubWindow() && activeSubWindow()->saveAs())
        ui.statusBar->showMessage(tr("文件保存成功"), 2000);
}

void texteditor::on_action_Exit_triggered()
{
    qApp->closeAllWindows();
}

void texteditor::on_action_Undo_triggered()
{
    activeSubWindow()->undo();
}

void texteditor::on_action_Redo_triggered()
{
    activeSubWindow()->redo();
}

void texteditor::on_action_Cut_triggered()
{
    activeSubWindow()->cut();
}

void texteditor::on_action_Copy_triggered()
{
    activeSubWindow()->copy();
}

void texteditor::on_action_Paste_triggered()
{
    activeSubWindow()->paste();
}

void texteditor::on_action_Close_triggered()
{
    ui.mdiArea->closeActiveSubWindow();
}

void texteditor::on_action_CloseAll_triggered()
{
    ui.mdiArea->closeAllSubWindows();
}

void texteditor::on_action_Next_triggered()
{
    ui.mdiArea->activateNextSubWindow();
}

void texteditor::on_action_Previous_triggered()
{
    ui.mdiArea->activatePreviousSubWindow();
}

void texteditor::on_action_Title_triggered()
{
    ui.mdiArea->tileSubWindows();
}

void texteditor::on_action_Cascade_triggered()
{
    ui.mdiArea->cascadeSubWindows();
}


void texteditor::closeEvent(QCloseEvent *event)
{
    ui.mdiArea->closeAllSubWindows();
    if(ui.mdiArea->currentSubWindow())
        event->ignore();
    else
    {
        writeSettings();
        event->accept();
    }
}
